<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	
	<title>Confessions</title>
	
	<meta name="viewport" content="width=device-width; initial-scale=1.0" />
 	<link rel="stylesheet" href="css/jquery.mobile-1.3.2.css" />
 	<link rel="stylesheet" href="css/global.css" />
  
	<script type="text/javascript" charset="utf-8" src="js/cordova-2.9.0.js"></script>
	<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
   	<script type="text/javascript" src="js/jquery.mobile-1.3.1.min.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/library.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/common.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/localize.js"></script>  
	<script type="text/javascript" charset="utf-8" src="js/waypoints.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/waypoints-infinite.js"></script>    
 	<script>
 	
		var category = "";
		var page = 1;
	
	 	$(document).on("pagebeforeshow", "#main",function(event){
	 		//alert(1);
	 		//window.location.href="listByCategory.html";
	 		category = getParameter('category'); 
	 		document.addEventListener("deviceready", onDeviceReady, true); 
	 	});	
	 	 		
		function onDeviceReady() {
	        excecuteLocalization(["main","global"]);
			loadConfessions();
			loadCategories();
			
			$('#confession_text').on('keyup blur', function() {
				//alert(1);
				
				var text = $('#confession_text').val();				
				text = text.replace('  ', ' ');
				$('#confession_text').val(text)
				
				$("#charCount").html(text.length);
				
				if(text.length >= MINIMUM_CHARS_CONFESSION){
					if(!$('#categoriesField').is(":visible")){
						$('#categoriesField').fadeIn();
					}
					if(!$('#saveButton').is(":visible")){
						$('#saveButton').fadeIn();
					}
				} else{
					$("#saveButton").fadeOut();
					$('#categoriesField').fadeOut();
				}		
		    });		
			
			var minCharsText = $("#minCharsContainer").html();
			minCharsText = minCharsText.replace("app.minchars", MINIMUM_CHARS_CONFESSION);
			$("#minCharsContainer").html(minCharsText);
	    }
		
		function loadConfessions(){
			//alert(category);
	 		$("#errorMsg").html("");
	 		
	 	  	var url = appURL + "/getConfessionsByCategory.php";
	 	  	//alert(globalLocale);
	 	  	//alert(url);
	 	  	
		 	$.mobile.loadingMessage = "Loading...";
		 	$.mobile.loading('show');
	 		
		 	$.ajax({
		        url: 		url,
		        type: 		'post',
		        dataType: 	'json',
	        	data: 		{ category: "", page: page, languageCode: globalLocale },
	        	statusCode: {
					  		404: function() {
					  			alert('Could not contact server.');
					  		},
					  		500: function() {
					  			alert('A server-side error has occurred.');
					  		}
				},
	        	success: 	function(data) {
				        		//alert("Message: " + data.status);
					 			if(data.status == "ok"){
			
					 				var arrConfessions = data.confessions;
					 			 	var html='';
					 			    
					 			 	for (var i = 0; i < arrConfessions.length; i++) {
					 			    	//alert(arrConfessions[i].datetime);
					 			        html += getNewHTMLNode(arrConfessions[i].confession, arrConfessions[i].datetime, arrConfessions[i].id);
					 			    }
					 			    //alert(html);
					 			    $('#confessions').append(html);
					 			    
					 			   	if(data.lastPage){
					 			   		//alert("lastPage");
					 			 		$('#confessions').waypoint('destroy');
					 			 		$('#buttonMore').hide();
					 			 	} else {
					 			   		//alert("are more!");
						 			   	$('#confessions').waypoint('infinite', {
						 			   	  	container: 'auto',
							 			    items: '.infinite-item',
							 			    more: '.infinite-more-link',
							 			    offset: 'bottom-in-view',
							 				loadingClass: 'infinite-loading',
							 			    onBeforePageLoad: $.noop,
							 			    onAfterPageLoad: loadMore
						 			   	});
					 			    }
					 			 	
					 			}else{
					 			 	//alert("No se pudo enviar email");
					 			 	$("#errorMsg").html(data.message);
					 			}
					 			$.mobile.loading('hide');
											
		        },
        		fail:	function(error){
                 		alert("Mal: " + JSON.stringify(error));                   		
           		}
		    });
	 	}
		
		
		function loadMore(){
			//alert("loading!");
			page = page + 1;
			loadConfessions();
		}
		
		function getNewHTMLNode(confession, datetime, id){			
			//'<p>Date: ' + arrConfessions[i].datetime + '<br><br>' + arrConfessions[i].confession + '</p>';
			var html="";
			
			html += '<article>';
			html += '	<p>';
			//html += '			' + id + '			' + datetime;
			html += datetime;
			html += '	</p>';
			html += '	<p><div style="word-wrap: break-word;">';
			html += '			' + confession;
			html += '	</div></p>';
			html += '</article>';
				            	
			return html;			
		}
		
		function saveConfession(){
			
			var parameter = '';
	 		$("#errorMsg").html("");
	 		
	 		var confession = $("#confession_text").val();
	 		var category = $("#categories").val();
	 		
	 		if(confession==""){
	 			alert($("#completeconfessionTag").html());
	 			return;
	 		}
	 		
	 	  	var url = appURL + "/saveConfessionsByCategory.php";
	 	  	//alert(url);
	 	  	
		 	$.mobile.loadingMessage = "Loading...";
		 	$.mobile.loading('show');
	 		
		 	$.ajax({
		        url: 		url,
		        type: 		'post',
		        dataType: 	'json',
	        	data: 		{ category: category, confession: confession, languageCode: globalLocale },
	        	statusCode: {
					  		404: function() {
					  			alert('Could not contact server.');
					  		},
					  		500: function() {
					  			alert('A server-side error has occurred.');
					  		}
				},
	        	success: 	function(data) {
				        		//alert("Message: " + data.status);
					 			if(data.status == "ok"){
					 				$("#confession_text").val("");
							 		$("#categories").val("-1");
							 		$("#categoriesField").fadeOut();
							 		//$("#errorMsg").html($("#datasavedTag").html());
							 		alert($("#datasavedTag").html());
							 		setTimeout(function() {
							 			$("#errorMsg").fadeOut("slow");
								 		$("#errorMsg").html("");
							 			$("#errorMsg").show();
							 			
							 			$('#confessions').html("");
							 			page = 1;
							 			loadConfessions();
							 			
							 		}, 1000);
					 			 	
					 			}else{
					 			 	//alert(data.message);
					 			 	$("#errorMsg").html(data.message);
					 			}
		 						$.mobile.loading('hide');												
		        },
        		fail:	function(error){
                 		alert("Mal: " + JSON.stringify(error));  
 						$.mobile.loading('hide');                 		
           		}
		    });
	 	}
		
		function loadCategories(){
			
			var parameter = '';
	 		$("#errorMsg").html("");
	 		
	 	  	var url = appURL + "/getCategories.php"
	 	  	//alert(url);
	 	  	
	 	  	
		 	$.mobile.loadingMessage = "Loading...";
		 	$.mobile.loading('show');
	 		
		 	$.getJSON(url, { type: parameter, languageCode: globalLocale }).done(function(data) {
	 			//alert("Message: " + data.status);
	 			if(data.status == "ok"){
	 				
		 			//alert("Categories: " + data.categories);
	 			 	//$("#errorMsg").html("OK");

	 			 	var arrCategories = data.categories;
	 			 	var html='';
	 			 	//var html+='<option value="-1" selected="selected">All</option>';
	 			    
	 			 	for (var i = 0; i < arrCategories.length; i++) {
	 			    	//alert(arrCategories[i].category);
	 			        html += '<option value="' + arrCategories[i].id + '">' + arrCategories[i].category + '</option>';
	 			    }
	 			    //alert(html);
	 			    $('#categories').append(html);
	 			 	
	 			}else{
	 			 	//alert(data.message);
	 			 	$("#errorMsg").html(data.message);
	 			}
	 			$.mobile.loading('hide');
	 		});
	 	}
		
	 	
	</script>
</head>
<body style="text-align:center;">

<div  data-role="page" style="display:none;" id="main" data-theme="b">
	<div data-role="panel" data-position="right" data-position-fixed="false" data-display="overlay" id="menu-panel" data-theme="a">

		<ul data-role="listview" data-theme="a" data-divider-theme="a" style="margin-top:-16px;" class="nav-search">
			<li data-icon="delete" style="background-color:#111;">
				<a href="#header" data-rel="close"><span data-translate="localize">global.close_menu</span></a>
			</li>
			<li>
				<a href="javascript:backToHome();"><span data-translate="localize">global.go_home</span></a>
			</li>
			<li>
				<a href="javascript:listByCategory();"><span data-translate="localize">global.read_by_category</span></a>
			</li>
			<li>
				<a href="javascript:window.location.href='settings.html'"><span data-translate="localize">global.settings</span></a>
			</li>
			<li>
				<a href="javascript:exitAPP();"><span data-translate="localize">global.exit</span></a>
			</li>
		</ul>
		<span data-translate="localize" id="confirm_msgTag" style="display:none;">global.confirm_msg</span>
		<!-- panel content goes here -->
	</div><!-- /panel -->

	<div  data-role="header" id="header"  data-position="fixed">
		<img border="0" src="images/img-logo.png" alt="Logo" height="35" style="float:left; display:inline"/>
		<a href="javascript:openMenu();" data-icon="gear" class="ui-btn-right" id="openMenuButton"><span data-translate="localize">global.menu</span></a>
	</div>  
	<div  data-role="content">
	
		<div class="main-container" id='contentId'>
			
			<table style="width: 100%">
				<tr>
					<td>		
						<div data-role="fieldcontain">
							<div class="errorMsg" id="errorMsg"></div>
							<div style="margin-top:5px;"><span data-translate="localize" >write_your_confession</span></div>
							<textarea rows="5" cols="20" id="confession_text"></textarea>
							<span data-translate="localize" class="charcount">chars</span>
							<span class="charcount">:&nbsp;</span>
							<span id="charCount"  class="charcount">0</span>
							<span>&nbsp;&nbsp;</span>
							<span data-translate="localize" class="charcount" id="minCharsContainer">min_chars</span>
						</div>							
						<div data-role="fieldcontain" style="display:none;" id="categoriesField">
							<span data-translate="localize">optional_category</span>
							<select id='categories'></select>
						</div>
						
					</td>
				</tr>
				<tr>
					<td>
						<div id="buttonMore" style="display:none;" class="infinite-more-link"><button onclick="loadMore();">More...</button></div>
						<div id="buttonList" style="display:none;"><button onclick="window.location.href='listByCategory.html';">List</button></div>
						<div style="display:none;" id="saveButton"><button id="higlighted" onclick="saveConfession();"><span data-translate="localize">save_confession</span></button></div>	
					</td>
				</tr>
			</table>
		
			
			<span data-translate="localize">read_confessions</span>
			<a class="infinite-more-link" href="http://nico287.dyndns.org:81/Noticiasonline/mobileapps/confessions/dummy.php"></a>
			<section id="confessions" class="infinite-container">
	        </section>
        
			
			<span data-translate="localize" id="datasavedTag" style="display:none;">global.saved_msg</span>
			<span data-translate="localize" id="completeconfessionTag" style="display:none;">complete_confession</span>
			
			 <!--
			<div  data-role="footer">
				<button class="button-main-small" onclick="exitAPP();">Salir</button>
			</div>
			  -->
		</div>
	</div>
</div>
</body>
</html>